package com.lastoffer2.activity;

import it.etna.common.DateUtil;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.lastct.dao.Location;
import com.lastct.dao.Offer;
import com.lastoffer2.R;
import com.lastoffer2.adapter.LocationSpinAdapter;
import com.lastoffer2.util.DatePickerFragment;
import com.lastoffer2.util.DateUtilExtra;
import com.lastoffer2.util.JSONConnector;
import com.lastoffer2.util.TimePickerFragment;

@SuppressLint("ShowToast") public class InsertOfferActivity extends FragmentActivity {

	private InsertOfferTask mInsertTask = null;
	private LoadDataTask mLoadDataTask = null;

	private String mShortDescription;
	private String mDescription;
	private String mNumMax;

	// UI references.
	private EditText mShortDescriptionView;
	private EditText mDescriptionView;
	private View mFormView;
	private View mStatusView;
	private TextView mStatusMessageView;
	private TextView mDataInizioPrenotazioneView;
	private TextView mDataFinePrenotazioneView;
	private TextView mOraInizioPrenotazioneView;
	private TextView mOraFinePrenotazioneView;
	private TextView mDataInizioOffertaView;
	private TextView mDataFineOffertaView;
	private TextView mOraInizioOffertaView;
	private TextView mOraFineOffertaView;
	
	private EditText mNumMaxView;
	private Spinner spinLocationView;
	private TextView mLocationIdView;
	private List<Location> locationList = new ArrayList<Location>();
	private Integer userId;
	
	private Integer idMod;
	private Integer idDupl;
	private Offer offer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_insert_offer);

		mLoadDataTask = new LoadDataTask();
		mLoadDataTask.execute((Void) null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.insert_offer, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.annulla_inserimento_offerta:
	            return true;
	        case R.id.conferma_inserimento_offerta:
	    		validationFields();
				return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}


	public void validationFields() {
		if (mInsertTask != null) {
			return;
		}

		// Reset errors.
		mShortDescriptionView.setError(null);
		mDescriptionView.setError(null);
		mNumMaxView.setError(null);
		
		mShortDescription = mShortDescriptionView.getText().toString();
		mDescription = mDescriptionView.getText().toString();
		mNumMax = mNumMaxView.getText().toString();
		
		boolean cancel = false;
		View focusView = null;

		if (TextUtils.isEmpty(mDescription)) {
			mDescriptionView.setError(getString(R.string.error_field_required));
			focusView = mDescriptionView;
			cancel = true;
		}

		if (TextUtils.isEmpty(mShortDescription)) {
			mShortDescriptionView.setError(getString(R.string.error_field_required));
			focusView = mShortDescriptionView;
			cancel = true;
		}
		
		if (TextUtils.isEmpty(mNumMax)) {
			mShortDescriptionView.setError(getString(R.string.error_field_required));
			focusView = mNumMaxView;
			cancel = true;
		}
		
		Integer numMax = 0;
		try{
			numMax = Integer.parseInt(mNumMax);
		}catch(Exception e) {
			mNumMaxView.setError(getString(R.string.error_field_numeric));
			focusView = mNumMaxView;
			cancel = true;
		}
		
		if (numMax<=0 || numMax>1000) {
			mNumMaxView.setError(getString(R.string.error_field_numeric_max_min));
			focusView = mNumMaxView;
			cancel = true;
		}
		

		if (cancel) {
			// There was an error
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform.
			mStatusMessageView.setText(R.string.insert_progress);
			showProgress(true);
			mInsertTask = new InsertOfferTask();
			mInsertTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mStatusView.setVisibility(View.VISIBLE);
			mStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mFormView.setVisibility(View.VISIBLE);
			mFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mFormView.setVisibility(show ? View.GONE : View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	public class InsertOfferTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			
			try {
				JSONConnector.insertNewOffer(mShortDescriptionView.getText().toString(),
											 mDescriptionView.getText().toString(),
											 mDataInizioPrenotazioneView.getText().toString()+" "+mOraInizioPrenotazioneView.getText().toString(),
											 mDataFinePrenotazioneView.getText().toString()+" "+mOraFinePrenotazioneView.getText().toString(),
											 mDataInizioOffertaView.getText().toString()+" "+mOraInizioOffertaView.getText().toString(),
											 mDataFineOffertaView.getText().toString()+" "+mOraFineOffertaView.getText().toString(),
											 mNumMaxView.getText().toString(),
											 mLocationIdView.getText().toString());
			} catch (Exception e) {
				return false;
			}
			
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mInsertTask = null;
			showProgress(false);

			if (success) {
				Toast.makeText(InsertOfferActivity.this, "Inserimento effettuato con successo", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(InsertOfferActivity.this, "Errore! inserimento non effettuato", Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected void onCancelled() {
			mInsertTask = null;
			showProgress(false);
		}
	}
	
	public class LoadDataTask extends AsyncTask<Void, Void, Boolean>{
		@Override
		protected Boolean doInBackground(Void... params) {
			
			try {
				
				Bundle b = getIntent().getExtras();
				if(b!=null) 
				{	idMod = b.getInt("idMod");
					idDupl = b.getInt("idDupl");
				
					// controllo se questi campi sono valorizzati
					if(idMod!=null) //si tratta di modifica...faccio una query e mi valorizzo i campi
						offer = JSONConnector.getOffer(idMod);
					
					else if(idDupl!=null) // si tratta di duplicazione del record
						offer = JSONConnector.getOffer(idDupl);
				}
				
				//per ora costante
				userId = 1;
				locationList = JSONConnector.getListLocationByUserId(userId);
				
			} catch (Exception e) {
				return false;
			}
			return true;
		}
		@Override
		protected void onPostExecute(Boolean v) {
			
			// Set up the form.
			mFormView = findViewById(R.id.form);
			mStatusView = findViewById(R.id.status);
			mStatusMessageView = (TextView) findViewById(R.id.status_message);
			
			mDataInizioPrenotazioneView = (TextView) findViewById(R.id.data_inizio_prenotazione);
			mDataFinePrenotazioneView = (TextView) findViewById(R.id.data_fine_prenotazione);
			mOraInizioPrenotazioneView = (TextView) findViewById(R.id.ora_inizio_prenotazione);
			mOraFinePrenotazioneView = (TextView) findViewById(R.id.ora_fine_prenotazione);
			mDataInizioOffertaView = (TextView) findViewById(R.id.data_inizio_offerta);
			mDataFineOffertaView = (TextView) findViewById(R.id.data_fine_offerta);
			mOraInizioOffertaView = (TextView) findViewById(R.id.ora_inizio_offerta);
			mOraFineOffertaView = (TextView) findViewById(R.id.ora_fine_offerta);
			
			if(offer!=null)
			{	mShortDescription = offer.getShortDescription();
				mDescription = offer.getDescription();
				mNumMax = ""+offer.getNumMax();
				mDataInizioPrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, offer.getDataInizioPrenotazione()));
				mDataFinePrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, offer.getDataFinePrenotazione()));
				mOraInizioPrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, offer.getDataInizioPrenotazione()));
				mOraFinePrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, offer.getDataFinePrenotazione()));
				mDataInizioOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, offer.getDataInizioOfferta()));
				mDataFineOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, offer.getDataFineOfferta()));
				mOraInizioOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, offer.getDataInizioOfferta()));
				mOraFineOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, offer.getDataFineOfferta()));
			}
			else
			{	mDataInizioPrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.today()));
				mDataFinePrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.today()));
				mOraInizioPrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, DateUtil.now()));
				mOraFinePrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, DateUtil.now()));
				mDataInizioOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.today()));
				mDataFineOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.today()));
				mOraInizioOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, DateUtil.now()));
				mOraFineOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_TIME, DateUtil.now()));
			}
			
			mShortDescriptionView = (EditText) findViewById(R.id.shortdescription);
			mShortDescriptionView.setText(mShortDescription);
			mDescriptionView = (EditText) findViewById(R.id.description);
			mDescriptionView.setText(mDescription);
			mNumMaxView = (EditText) findViewById(R.id.num_max);
			mNumMaxView.setText(mNumMax);
			
			spinLocationView = (Spinner) findViewById(R.id.spinner_location);
			mLocationIdView = (TextView) findViewById(R.id.location_id);
			
			LocationSpinAdapter aa = new LocationSpinAdapter(InsertOfferActivity.this,android.R.layout.simple_spinner_item,locationList);
			aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinLocationView.setAdapter(aa);
			
			spinLocationView.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
					mLocationIdView.setText(""+locationList.get(position).getId());
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					
				} 
			});
		}

		
		
	}
	
	public void showDatePicker(View v) throws ParseException {
		  DatePickerFragment date = new DatePickerFragment();
		  
		  TextView view = (TextView)v;
		  Date data = DateUtil.parse(DateUtilExtra.FORMAT_DATE, view.getText().toString());
		  Calendar cal = Calendar.getInstance();
		  cal.setTime(data);
		  int day = cal.get(Calendar.DAY_OF_MONTH);
		  
		  Bundle args = new Bundle();
		  args.putInt("year", DateUtil.year(data));
		  args.putInt("month", DateUtil.month(data)-1);
		  args.putInt("day", day);
		  date.setArguments(args);
		  /**
		   * Set Call back to capture selected date
		   */
		  OnDateSetListener ondate = null;
		  switch (v.getId()) {
			case R.id.data_inizio_prenotazione:
				ondate = new OnDateSetListener() {
					  @Override
					  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						  mDataInizioPrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.creaData(year, monthOfYear+1, dayOfMonth)));
					  }
				};
				break;
	
			case R.id.data_fine_prenotazione:
				ondate = new OnDateSetListener() {
					  @Override
					  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						  mDataFinePrenotazioneView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.creaData(year, monthOfYear+1, dayOfMonth)));
					  }
				};
				break;
				
			case R.id.data_inizio_offerta:
				ondate = new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						mDataInizioOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.creaData(year, monthOfYear+1, dayOfMonth)));
					}
				};
				break;
				
			case R.id.data_fine_offerta:
				ondate = new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						mDataFineOffertaView.setText(DateUtil.format(DateUtilExtra.FORMAT_DATE, DateUtil.creaData(year, monthOfYear+1, dayOfMonth)));
					}
				};
				break;
				
			default:
				break;
		}
		  
		date.setCallBack(ondate);
		date.show(getSupportFragmentManager(), "Date Picker");
	}

	public void showTimePicker(View v) {
		  TimePickerFragment date = new TimePickerFragment();
		  
		  TextView view = (TextView)v;
		  String[] orario = view.getText().toString().split(":");
		  
		  Bundle args = new Bundle();
		  args.putInt("hours", Integer.parseInt(orario[0]));
		  args.putInt("minutes", Integer.parseInt(orario[1]));
		  date.setArguments(args);
		  /**
		   * Set Call back to capture selected date
		   */
		  OnTimeSetListener ontime = null;
		  switch (v.getId()) {
			case R.id.ora_inizio_prenotazione:
				ontime = new OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mOraInizioPrenotazioneView.setText(hourOfDay+":"+minute);
					}
				};
				break;
	
			case R.id.ora_fine_prenotazione:
				ontime = new OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mOraFinePrenotazioneView.setText(hourOfDay+":"+minute);
					}
				};
				break;
				
			case R.id.ora_inizio_offerta:
				ontime = new OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mOraInizioOffertaView.setText(hourOfDay+":"+minute);
					}
				};
				break;
				
			case R.id.ora_fine_offerta:
				ontime = new OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mOraFineOffertaView.setText(hourOfDay+":"+minute);
					}
				};
				break;
				
			default:
				break;
		}
		  
		date.setCallBack(ontime);
		date.show(getSupportFragmentManager(), "Time Picker");
	}
	
	
}
